import store from '@/store';
import router from '@/router';
// import { ipcRenderer } from 'electron'

import nedb from '@/libs/util.db';
import base64 from '@/libs/base64.js';
// import { closeWebsocket } from '../websocket';

/**
 * 退出登陆
 */
function deviceExitNoticeHandle(msg) {
    console.log('退出登陆成功');
    console.log(msg);
    store.dispatch('SetToken', '');
    store.dispatch('SetLogin', false);
    if(store.getters.dialogLock === 6) {
        store.dispatch('SetDialogLock', 0);
        store.dispatch('SetDialog', '');
    }
    // ipcRenderer.send('operations', 'logout')
    router.replace('/');
    // closeWebsocket();
}

/**
 * 从服务端获取历史消息
 * @param {*} msg
 */
function queryHistoryMessageRespHandle(msg) {
    console.log('从服务端获取指定好友的历史消息：queryHistoryMessageRespHandle');
    let data = msg.message ? JSON.parse(msg.message) : {};
    // console.log(data)
    if(data.resultList && data.resultList.length > 0) {
        let messages = data.resultList;
        console.log(messages);
        let wechatId = messages[0].wechatId;
        let friendId = messages[0].friendId;
        let userId = store.getters.userId;
        nedb.chats.find(
            {
                user: userId,
                WeChatId: wechatId,
                FriendId: friendId
            },
            (err, docs) => {
                // console.log(err || docs)
                if(err) return;
                let alreadyExist = []; // 已经存在的会话
                let insertChats = []; // 需要insert的会话
                for(const doc of docs) {
                    alreadyExist.push(doc.msgSvrId);
                }

                for(const chat of messages) {
                    if(alreadyExist.indexOf(chat.msgSvrId) < 0) {
                        insertChats.push(chat);
                    }
                }

                if(insertChats.length === 0) return;
                let chats = [];
                for(const chat of insertChats) {
                    let nc = {};
                    nc.Content = chat.content ? base64.b64EncodeUnicode(chat.content) : '';
                    nc.ContentType = chat.contentType;
                    nc.IsSend = chat.isSend === 'true' ? 1 : 0;
                    nc.MsgId = chat.msgId ? chat.msgId : '';
                    nc.msgSvrId = chat.msgSvrId;
                    nc.createTime = chat.create_time;
                    nc.FriendId = chat.friendId;
                    nc.WeChatId = chat.wechatId;
                    nc.user = userId;
                    chats.push(nc);
                }
                nedb.chats.insert(chats, (err, newDocs) => {
                    if(err) return;
                    store.dispatch('conversation/SetCurrentChats');
                });
            }
        );
    }else {
        console.log('服务端没有历史消息');
    }
}

/**
 * 从服务端获取历史消息
 * @param {*} msg
 */
function historyMessageListRespHandle(msg) {
    console.log('从服务端获取历史消息：historyMessageListRespHandle');
    // console.log(msg)
    let data = msg.message ? JSON.parse(msg.message) : {};
    // console.log(data)
    if(data.resultList && data.resultList.length > 0) {
        let messages = data.resultList;
        console.log(messages);
        let chats = [];
        let userId = store.getters.userId;

        for(const chat of messages) {
            let nc = {};
            nc.Content = chat.content ? base64.b64EncodeUnicode(chat.content) : '';
            nc.ContentType = chat.contentType;
            nc.IsSend = chat.isSend ? 1 : 0;
            nc.MsgId = chat.wechatId ? chat.wechatId : '';
            nc.msgSvrId = chat.msgSvrId;
            nc.createTime = chat.create_time;
            nc.FriendId = chat.friendId;
            nc.WeChatId = chat.wechatId;
            nc.user = userId;
            chats.push(nc);
        }
        console.log(chats);

        nedb.chats.insert(chats, (err, newDocs) => {
            console.log(err || newDocs);
            store.dispatch('conversation/SetCurrentChats');
        });
    }else {
        console.log('服务端没有历史消息');
    }
}

/**
 * 公共术语
 * @param {*} msg
 */
function getCommonTermsRespHandle(msg) {
    // console.log('返回的公共术语:getCommonTermsRespHandle')
    // console.log(msg)
    if(msg.message) {
        let message = JSON.parse(msg.message);
        // console.log(message)
        store.dispatch('conversation/SetPublicReply', message);
    }else {
        console.log('++++++没有公共术语+++++++');
    }
}

/**
 * 标签
 * @param {*} msg
 */
function getCommonTagsRespHandle(msg) {
    let tags = JSON.parse(msg.message);
    console.log('从服务端拉取标签：GetCommonTagsResp');
    console.log(tags);
    store.dispatch('conversation/SetTags', tags);
}
// =======================================================================
/**
 * 商务列表
 */
function getBuinessListRespHandle(msg) {
    let message = JSON.parse(msg.message);
    store.dispatch('chats/SetBusinessList', message);
}

/**
 * 定时任务列表
 */
function getTaskInfoListRespHandle(msg) {
    // console.log(msg)
    if(msg.message) {
        let messages = JSON.parse(msg.message);
        store.dispatch('SetTaskList', messages);
    }else {
        console.log('没有定时任务');
        console.log(msg);
    }
}

/**
 * 上传好友的备注
 * @param {*} msg
 */
function saveFriendTagDetailRespHandle(msg) {
    let message = JSON.parse(msg.message);
    console.log(message);
    // store.dispatch('record/SetCurrentRecord', message)
    // let db = store.getters.db
    // websql.updateFriendsLocal(db, message)
}

/**
 * 指定好友的备注
 */
function getWechatFriendDetailRespHandle(msg) {
    let friendInfo = JSON.parse(msg.message);
    console.log('从服务端获取当前好友的备注:GetWechatFriendDetailResp');
    console.log(friendInfo);
    // store.dispatch('record/SetCurrentRecord', friendInfo)
    // let db = store.getters.db
    // websql.updateFriendsLocal(db, friendInfo)
}

export default {
    getBuinessListRespHandle,
    getTaskInfoListRespHandle,
    getCommonTermsRespHandle,
    saveFriendTagDetailRespHandle,
    getWechatFriendDetailRespHandle,
    getCommonTagsRespHandle,
    deviceExitNoticeHandle,
    historyMessageListRespHandle,
    queryHistoryMessageRespHandle
};
